<template>
  <el-dialog
    :title="title"
    class="add-address-dialog"
    :visible="dialogVisible"
    width="600px"
    @close="closeDialog"
  >
    <div class="address-form-wrapper">
      <el-form
        ref="addressForm"
        :model="addressForm"
        :rules="addressFormRules"
        label-position="right"
        label-width="80px"
      >
        <el-form-item label="接收科室" prop="departCode">
          <el-select v-model="addressForm.departCode" placeholder="请选择">
            <el-option
              v-for="items in officList"
              :key="items.code"
              :label="items.name"
              :value="items.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="linkMan">
          <el-input v-model="addressForm.linkMan" />
        </el-form-item>
        <el-form-item label="联系电话" prop="linkPhone">
          <el-input v-model="addressForm.linkPhone" :maxlength="11" />
        </el-form-item>
        <el-form-item label="是否默认" prop="defaultStatus">
          <el-select v-model="addressForm.defaultStatus" placeholder="请选择">
            <el-option
              v-for="items in statusData"
              :key="items.value"
              :label="items.label"
              :value="items.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="省" prop="provinceCode">
          <el-select
            v-model="addressForm.province"
            placeholder="请选择"
            @change="provinceMethod"
          >
            <el-option
              v-for="items in provinceData"
              :key="items.value"
              :label="items.label"
              :value="items.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="cityCode" label="市">
          <el-select
            v-model="addressForm.city"
            placeholder="请选择"
            @change="cityMethod"
          >
            <el-option
              v-for="items in cityData"
              :key="items.value"
              :label="items.label"
              :value="items.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="countyCode" label="区">
          <el-select
            v-model="addressForm.county"
            placeholder="请选择"
            @change="countyMethod"
          >
            <el-option
              v-for="items in countyData"
              :key="items.value"
              :label="items.label"
              :value="items.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="addressForm.address" />
        </el-form-item>
        <el-form-item label="标签" prop="tag">
          <el-input v-model="addressForm.tag" />
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" :loading="loading" @click="confirmDialog"
        >确定</el-button
      >
      <el-button @click="closeDialog">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
/* eslint-disable */

import ElSelectArea from '@femessage/el-select-area';
import { phone, realName } from '@const/formValidate';
import { editKSList } from '@api/hossyn-order-center';

const validateLocation = (rule, value, callback) => {
  const hasEmpty =
    value.length === 0 || value.some((item) => item.length === 0);
  if (hasEmpty) {
    callback(new Error('请选择地址区域'));
  } else {
    callback();
  }
};

export default {
  name: 'AddAddressDialog',
  components: { ElSelectArea },
  props: {
    title: {
      type: String,
      default: '编辑收件地址',
    },
    departCodeData: {
      type: String,
      default: () => {},
    },
    //
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    formData: {
      type: Object,
      default: () => {},
    },
    loading: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      officList: [],
      provinceData: [],
      cityData: [],
      countyData: [],
      statusData: [
        { label: '是', value: 1 },
        { label: '否', value: 0 },
      ],
      areaList: {
        provinceCode: '',

        cityCode: '',
        countyCode: '',
      },
      queryArea: '/guoke-deepexi-interface-center/api/v1/mdm/code/area/list', // 省市查询接口
      addressForm: {
        tag: '',
        departName: '',
        departCode: '',
        linkMan: '',
        linkPhone: '',
        province: '',
        address: '',
        defaultStatus: '',
        cityId: '',
        city: '',
        county: '',
        detailedAddress: '',
        location: [],
        provinceId: '',
      },
      isadd: true,
      addressFormRules: {
        departCode: [
          { required: true, message: '请输入科室名称', trigger: 'change' },
        ],
        linkMan: [
          { required: true, message: '请输入联系人', trigger: 'change' },
        ],
        linkPhone: phone(),
        // status: [
        //   { required: true, message: '请选择是否有效', trigger: 'change' },
        // ],
        // provinceCode: [
        //   { required: true, message: '请输入省', trigger: 'change' },
        // ],
        // cityCode: [{ required: true, message: '请输入市', trigger: 'change' }],
        // countyCode: [
        //   { required: true, message: '请输入区', trigger: 'change' },
        // ],
        // address: [
        //   { required: true, message: '请输入详细地址', trigger: 'change' },
        // ],
      },
      tableData: this.invoiceData,
    };
  },
  watch: {
    formData(val) {
      this.$nextTick(() => {
        if (Object.keys(val).length === 0) {
          this.$refs.addressForm.resetFields();
          this.addressForm.location = [];
        } else {
          this.addressForm = { ...val };
          this.getCityList();
          this.getCountyList();
          this.editOfficeListMethod();
        }
      });
    },
  },
  mounted() {
    this.getDefaultProvinceData();
  },
  methods: {
    editOfficeListMethod() {
      const hospitalCode = {
        hospitalCode: this.$route.query.hospitalCode,
      };
      this.$axios({
        method: 'post',
        url: editKSList,
        data: hospitalCode,
      })
        .then((res) => {
          this.officList = res.data.payload || [];
        })
        .catch((err) => {});
    },
    // 初始化默认获取省的数据
    getDefaultProvinceData() {
      this.$axios({
        method: 'get',
        url: this.queryArea,
        params: {
          countryCode: 'CN',
        },
      })
        .then((res) => {
          const result = res.data.payload;
          this.provinceData = this.handleData(result);
          // 清空该行下的市和区
        })
        .catch(() => {
          // this.provinceData[0] = []
        });
    },
    // 修改省的数据时，获取市的数据
    provinceMethod() {
      this.addressForm.province = this.provinceData.find((item) =>
        Object.is(this.addressForm.province, item.value)
      ).value;
      // 清空市、区
      this.addressForm.city = '';
      this.addressForm.cityId = '';
      this.addressForm.county = '';
      if (this.addressForm.province) this.getCityList();
    },
    // 获取市数据的接口调用
    getCityList() {
      this.$axios({
        method: 'get',
        url: this.queryArea,
        params: {
          provinceCode: this.addressForm.province,
        },
      })
        .then((res) => {
          const result = res.data.payload;
          this.cityData = this.handleData(result);
        })
        .catch(() => {
          // this.cityData[this.tableIndex] = []
        });
    },
    // 修改市的数据时，获取区的数据
    cityMethod() {
      this.addressForm.city = this.cityData.find((item) =>
        Object.is(this.addressForm.city, item.value)
      ).value;
      this.addressForm.county = '';
      this.addressForm.areaId = '';
      if (this.addressForm.city) this.getCountyList();
    },
    handleData(result) {
      const arr = [];
      for (const key in result) {
        arr.push({
          value: [key][0],
          label: result[key],
        });
      }
      return arr;
    },
    // 获取区数据的接口
    getCountyList() {
      this.$axios({
        method: 'get',
        url: this.queryArea,
        params: {
          cityCode: this.addressForm.city,
        },
      })
        .then((res) => {
          const result = res.data.payload;
          this.countyData = this.handleData(result);
        })
        .catch(() => {});
    },
    countyMethod() {
      this.addressForm.county = this.countyData.find((item) =>
        Object.is(this.addressForm.county, item.value)
      ).value;
    },
    closeDialog() {
      this.$emit('closeDialogConsignee');
    },
    confirmDialog() {
      this.$refs.addressForm.validate((valid) => {
        if (valid) {
          const data = JSON.parse(JSON.stringify(this.addressForm));

          let depart;
          let province;
          let city;
          let county;
          if (this.formData.departCode !== this.addressForm.departCode) {
            depart = this.officList.find(
              (item) => item.code === this.addressForm.departCode
            );
            data.departCode = depart.code;
            data.departName = depart.name;
          }
          if (this.formData.province !== this.addressForm.province) {
            province = this.provinceData.find(
              (item) => item.value === this.addressForm.province
            );
            city = this.cityData.find(
              (item) => item.value === this.addressForm.city
            );
            county = this.countyData.find(
              (item) => item.value === this.addressForm.county
            );
            data.province = province.label;
            data.provinceCode = province.value;
            data.city = city.label;
            data.cityCode = city.value;
            data.county = county.label;
            data.countyCode = county.value;
          }
          delete data.location;
          this.$emit('confirmDialogConsignee', data);
        }
      });
    },
  },
};
</script>

<style lang="less">
.add-address-dialog {
  .address-form-wrapper {
    width: 400px;
    margin: auto;

    .el-select-area {
      .select-area-item {
        width: 100px;

        &:last-child {
          margin-right: 0;
        }
      }
    }
  }

  .dialog-footer {
    text-align: center;
  }
}
</style>
